/********************************************************************
 
 Copyright (C), 2012年 dhc. All rights reserved.
 
 Filename: 	    MailMessageComposer.h
 
 Author:        muzongcun
 
 Version:       1.0
 
 Description:   MailMessageComposer
 
 History:
 
 muzongcun    2012/3/10     1.0     Create
 
 *********************************************************************/

#import "MailMessageComposer.h"
#import "MailDetailMessage.h"
#import "Session.h"
#import "XmlRpc.h"
#import "GUID.h"

//控件的摆放位置
#define CONTROL_VIEW_HEIGH  35
#define CONTROL_VIEW_CENTER 35.0/2

//增加联系人的坐标位置
#define ADD_CONTACT_HEIGH   30
#define ADD_CONTACT_CENTER  30.0/2

@implementation MailMessageComposer

@synthesize m_navBar;
@synthesize m_rect;
@synthesize m_mailDetailMessage;
@synthesize m_mailComType;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
	if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) 
	{
        m_offsetFlag              = NO;
        m_mailComType             = MAX_COMPOSER;
        m_mailDetailMessage       = nil;
		m_receiverRowIndex        = 1;
        m_ccReceiverRowIndex      = 1;
		m_indexOfFirstNewLine     = 0;
        m_ccIndexOfFirstNewLine   = 0;
        
        m_totalAddrArray = [[NSMutableArray alloc] initWithCapacity:0];
        m_sendAddrArray  = [[NSMutableArray alloc] initWithCapacity:0];
        m_ccAddrArray    = [[NSMutableArray alloc] initWithCapacity:0];
	}
	return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil receiverObj:(NSDictionary*)rec
{
	m_receiverObj = [rec retain];
	
	return [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
}
- (id)initWithOwner:(UIViewController *)owner
{
    UIButton *playNowButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 20, 40)];
    playNowButton.titleLabel.text=@"";
    [playNowButton addTarget:self action:@selector(AgoList) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *bar =[[UIBarButtonItem alloc] initWithCustomView:playNowButton];
    [playNowButton release];
    //self.buttonOwner = owner;
    return (id)bar;
}
- (void)viewDidLoad 
{
    //最上面的bar
    m_navBar=[[UINavigationBar alloc]init];
    m_navBar.frame = CGRectMake(0, 0, 320, 44);

    UIImage* imageBar = [UIImage imageNamed:PIC_MAIL_TOP_BAR];

    NSString* devVersion = [[UIDevice currentDevice] systemVersion];
    if ([devVersion compare:@"4.3.3"] == 0)
    {
        [m_navBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)];
        [m_navBar setTintColor:NAVIGATION_BAR_COLOR];
    }else
    {
        [m_navBar setBackgroundImage:imageBar forBarMetrics:UIBarMetricsDefault];
    }
    //[imageBar release];
    
    //撰写邮件标题
    m_barTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(115.0, 5.0, 100.0, 32.0)];
    [m_barTitleLabel setBackgroundColor:[UIColor  clearColor]];
    m_barTitleLabel.textColor = [UIColor whiteColor];
    m_barTitleLabel.text = @"撰写邮件";
    
    //TOP BAR 右边的发送按钮
    UIButton* barSendBut = [[UIButton alloc] initWithFrame:CGRectMake(215.0, 0.0, 55.5, 44.0)];
    UIImage *barSendButImageNormal = [UIImage imageNamed:PIC_MAIL_BAR_SEND_NORMAL];
    [barSendBut setBackgroundImage:barSendButImageNormal forState:UIControlStateNormal];
    UIImage *barSendButImagePressed = [UIImage imageNamed:PIC_MAIL_BAR_SEND_PRESS];
    [barSendBut setBackgroundImage:barSendButImagePressed forState:UIControlStateHighlighted];
    [barSendBut setTitle:@"" forState:UIControlStateNormal];
    [barSendBut addTarget:self action:@selector(onSend:) forControlEvents:UIControlEventTouchUpInside];
    
    //TOP BAR 右边的保存按钮
    UIButton* barSaveBut = [[UIButton alloc] initWithFrame:CGRectMake(265.0, 0.0, 55.5, 44.0)];
    UIImage *barSaveButImageNormal = [UIImage imageNamed:PIC_MAIL_BAR_SAVE_NORMAL];
    UIImage *barSaveButImagePress = [UIImage imageNamed:PIC_MAIL_BAR_SAVE_PRESS];
    [barSaveBut setImage:barSaveButImageNormal forState:UIControlStateNormal];
    [barSaveBut setImage:barSaveButImagePress forState:UIControlStateHighlighted];
    [barSaveBut setTitle:@"" forState:UIControlStateNormal];
    [barSaveBut addTarget:self action:@selector(onSave:) forControlEvents:UIControlEventTouchUpInside];
    
    //返回按钮
    UIButton* barRetBut = [[UIButton alloc] initWithFrame:CGRectMake(5.0, 10.0, 50.0, 25.0)];
    [barRetBut setTitle:@" 返回" forState:UIControlStateNormal];
    UIFont *font              = [UIFont systemFontOfSize:14];
    barRetBut.titleLabel.font = font;
    UIImage *retButImageNormal = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_NORMAL];
    [barRetBut setBackgroundImage:retButImageNormal forState:UIControlStateNormal];
    UIImage *retButImagePressed = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_PRESS];
    [barRetBut setBackgroundImage:retButImagePressed forState:UIControlStateHighlighted];
    [barRetBut addTarget:self action:@selector(onNavigation) forControlEvents:UIControlEventTouchUpInside];
    
    //添加button到topbar上
    [m_navBar addSubview:barRetBut];
    [m_navBar addSubview:barSendBut];
    [m_navBar addSubview:barSaveBut];
    [m_navBar addSubview:m_barTitleLabel];
    
    [barRetBut release];
    [barSendBut release];
    [barSaveBut release];
    
    
    //创建tableview
	m_mainView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 44.0, 320.0, 480-20-44-49) style:UITableViewStylePlain];
	m_mainView.delegate   = self;
	m_mainView.dataSource = self;
	//mainView.scrollEnabled = NO;
	m_mainView.allowsSelection = NO;
	m_rect = m_mainView.frame;
	m_toContainerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, CONTROL_VIEW_HEIGH)];
	UILabel *rLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 70.0, CONTROL_VIEW_HEIGH)];
	rLabel.text = @"收件人:";
	rLabel.font = [UIFont systemFontOfSize:18];
	rLabel.textColor = [UIColor blackColor];
	[m_toContainerView addSubview:rLabel];
    [rLabel release];
    
    m_ccContainerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, CONTROL_VIEW_HEIGH)];
	UILabel *ccLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 70.0, CONTROL_VIEW_HEIGH)];
	ccLabel.text = @"抄 送:";
	ccLabel.font = [UIFont systemFontOfSize:18];
	ccLabel.textColor = [UIColor blackColor];
	[m_ccContainerView addSubview:ccLabel];
	[ccLabel release];
	
	m_subjectContainerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, CONTROL_VIEW_HEIGH)];
	UILabel *sLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0, 70.0, CONTROL_VIEW_HEIGH)];
	sLabel.text = @"主 题:";
	sLabel.font = [UIFont systemFontOfSize:18];
	sLabel.textColor = [UIColor blackColor];
	[m_subjectContainerView addSubview:sLabel];
	[sLabel release];
    
    m_contentContainerView  = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 248.0)];
    
    //邮件内容view
	m_contentTView = [[UITextView alloc] initWithFrame:CGRectMake(10.0, 0.0, 310.0, 800.0)];
    m_contentTView.returnKeyType = UIReturnKeyDefault;
	m_contentTView.delegate = self;
	m_contentTView.autocorrectionType = UITextAutocorrectionTypeNo;
	m_contentTView.autocapitalizationType = UITextAutocapitalizationTypeSentences;
	m_contentTView.font = [UIFont systemFontOfSize:14];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewTextDidChange:) name:UITextViewTextDidChangeNotification object:nil];
	[m_contentContainerView addSubview:m_contentTView];
    
    //设置滚动条不可用
    m_contentTView.showsVerticalScrollIndicator = NO;
    m_contentTView.scrollEnabled = NO;
    
    //存放button的view
    m_butContainerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 100.0)];
    
    //在键盘上，增加一个按钮
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 24)];  
    [topView setBarStyle:UIBarStyleBlackTranslucent];   
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];  

    //放置图片，不知道为什么ios4.3真机器不好用
//  UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithImage:downImage landscapeImagePhone:downImage style:UIBarButtonItemStyleDone target:self
//                                                                  action:@selector(dismissKeyBoard:)]; 
    
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:              UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard:)];
    
    //doneButton.width = 30;
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace,doneButton,nil];  
    [doneButton release];  
    [btnSpace release];   
    [topView setItems:buttonsArray];  
    //[contentTView setInputAccessoryView:topView];  
    [topView release];
    
    //主题编辑框
	m_subjectTF = [[UITextField alloc] initWithFrame:CGRectMake(70.0, 6.0, 230.0, CONTROL_VIEW_HEIGH)];
    m_subjectTF.returnKeyType =UIReturnKeyDone;
	m_subjectTF.delegate = self;
	m_subjectTF.autocorrectionType = UITextAutocorrectionTypeNo;
	m_subjectTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
	m_subjectTF.font = [UIFont systemFontOfSize:15];

    //触摸 textfield
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:nil];
    
    //触摸textView事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewTextDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:nil];
    
	//[subjectTF becomeFirstResponder];
	[m_subjectContainerView addSubview:m_subjectTF];
    [m_subjectTF release];
    
    //发送人编辑框
    m_toSendTF = [[UITextField alloc] initWithFrame:CGRectMake(80.0, 6.0, 200.0, CONTROL_VIEW_HEIGH)];
    m_toSendTF.returnKeyType =UIReturnKeyDone;
	m_toSendTF.delegate = self;
	m_toSendTF.autocorrectionType     = UITextAutocorrectionTypeNo;
	m_toSendTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
	m_toSendTF.font = [UIFont systemFontOfSize:15];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
	[m_toSendTF becomeFirstResponder];
	[m_toContainerView addSubview:m_toSendTF];
    [m_toSendTF release];
    
    //抄送者编辑框
    m_ccSendTF = [[UITextField alloc] initWithFrame:CGRectMake(70.0, 6.0, 216.0, CONTROL_VIEW_HEIGH)];
    m_ccSendTF.returnKeyType =UIReturnKeyDone;
	m_ccSendTF.delegate = self;
	m_ccSendTF.autocorrectionType     = UITextAutocorrectionTypeNo;
	m_ccSendTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
	m_ccSendTF.font = [UIFont systemFontOfSize:15];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
	//[ccSendTF becomeFirstResponder];
	[m_ccContainerView addSubview:m_ccSendTF];
    [m_ccSendTF release];
    
    //发送按钮
	m_sendBut = [UIButton buttonWithType:UIButtonTypeCustom];
	[m_sendBut setTitle:@"" forState:UIControlStateNormal];
    
    //设置按钮上的自体的大小
    m_sendBut.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    UIImage *buttonImageNormal = [UIImage imageNamed:PIC_MAIL_BOTTOM_SEND_NORMAL];
    [m_sendBut setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
    UIImage *buttonImagePressed = [UIImage imageNamed:PIC_MAIL_BOTTOM_SEND_PRESS];
    [m_sendBut setBackgroundImage:buttonImagePressed forState:UIControlStateHighlighted];
    [m_sendBut addTarget:self action:@selector(onSend:) forControlEvents:UIControlEventTouchUpInside];  //设置按钮点击事件
    m_sendBut.frame = CGRectMake(85, 5, 65.5, 43.5);
    
    //保存按钮
    m_saveBut = [UIButton buttonWithType:UIButtonTypeCustom];
	[m_saveBut setTitle:@"" forState:UIControlStateNormal];
    
    //设置按钮上的自体的大小
    m_saveBut.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    buttonImageNormal = [UIImage imageNamed:PIC_MAIL_BOTTOM_SAVE_NORMAL];
    buttonImagePressed = [UIImage imageNamed:PIC_MAIL_BOTTOM_SAVE_PRESS];
    [m_saveBut setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
    [m_saveBut setBackgroundImage:buttonImagePressed forState:UIControlStateHighlighted];
    [m_saveBut addTarget:self action:@selector(onSave:) forControlEvents:UIControlEventTouchUpInside];  //设置按钮点击事件
    m_saveBut.frame = CGRectMake(170, 5, 65.5, 43.5);
    [m_butContainerView addSubview:m_sendBut];
    [m_butContainerView addSubview:m_saveBut];
    m_mainView.tableFooterView = m_butContainerView;
    
    
	//[self.view insertSubview:mainView belowSubview:self.navBar];    //偏移改变.
    [self.view addSubview:m_mainView];
    [self.navigationController.view addSubview:m_navBar];
	[self addReceiver:m_receiverObj];
    
    //判断是邮件回复还是撰写邮件
    switch (m_mailComType) 
    {
        case NEW_COMPOSER:
        {

            break;
        }
            
        case REVERSE_COMPOSER:
        {
            if (m_mailDetailMessage != nil) 
            {
                //设置光标在起始位置
                NSRange range;
                range.location = 0;
                range.length  = 0;
                
                [m_contentTView becomeFirstResponder];
                UIFont *font          = [UIFont systemFontOfSize:14];
           
                NSString* strContent  = [NSString stringWithFormat:@"\r\r\r\r    －－－－原始邮件－－－－\r 在%@\r %@ 写道：\r\r %@\r\r\r\r\r\r\r\r\r\r\r\r\r",  m_mailDetailMessage.m_dateLabel.text,m_mailDetailMessage.m_sendLabel.text, m_mailDetailMessage.m_contentLabel.text];
                
                //计算文本内容的高度和宽度
                CGSize size = [strContent sizeWithFont:font constrainedToSize:CGSizeMake(310.0f, 2500.0f) lineBreakMode:  UILineBreakModeCharacterWrap];
                
                //设置输入文本框的高度
                m_contentTView.frame   = CGRectMake(10.0, 0.0, 310.0, size.height);
                NSString* strSubject = [NSString stringWithFormat:@"Re: %@", m_mailDetailMessage.m_subjectLabel.text];
                
                NSString* sendAddr = m_mailDetailMessage.m_sendLabel.text;
                sendAddr = [self getMailAddress:sendAddr];
                
                m_barTitleLabel.text  = @"邮件回复";
                m_subjectTF.text      = strSubject;
                m_toSendTF.text       = sendAddr;
                m_ccSendTF.text       = @"";
                m_contentTView.text   = strContent;
                m_contentTView.selectedRange = range;
                
            }
            break;
        }
        case TRANSMIT_COMPOSER:
        {
            if (m_mailDetailMessage != nil) 
            {
                //设置光标在起始位置
                NSRange range;
                range.location = 0;
                range.length  = 0;
                
                [m_contentTView becomeFirstResponder];
                UIFont *font          = [UIFont systemFontOfSize:14];
                
                NSString* content_txt = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"content_txt"];
 
                NSString* strContent  = [NSString stringWithFormat:@"\r\r\r\r    －－－－原始邮件－－－－\r 在%@\r %@ 写道：\r\r %@\r\r\r\r\r\r\r\r\r\r\r\r\r",  m_mailDetailMessage.m_dateLabel.text,m_mailDetailMessage.m_sendLabel.text, content_txt];
                
                //计算文本内容的高度和宽度
                CGSize size = [strContent sizeWithFont:font constrainedToSize:CGSizeMake(310.0f, 2500.0f) lineBreakMode:  UILineBreakModeCharacterWrap];
                
                //设置输入文本框的高度
                m_contentTView.frame   = CGRectMake(10.0, 0.0, 310.0, size.height);
                NSString* strSubject = [NSString stringWithFormat:@"Fw: %@", m_mailDetailMessage.m_subjectLabel.text];
                
                
                m_barTitleLabel.text  = @"邮件转发";
                m_subjectTF.text      = strSubject;
                //toSendTF.text       = mailDetailMessage.sendLabel.text;
                //ccSendTF.text       = @"";
                m_contentTView.text   = strContent;
                m_contentTView.selectedRange = range;
                
            }
            break;
        }
        default:
            break;
    }

}


//******************************************************
// Method:     getMailAddress
// Access:     public 
// Returns:    NSString
// Parameter:  originMailAddr
// Note:	   去掉 < > 提取邮件地址
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(NSString*) getMailAddress:(NSString*) originMailAddr
{
    NSString* temp    = originMailAddr;
    NSString *strSplit = temp;//@"<m>missed call</m>";
    NSRange rsrange;
    rsrange.length   = 0;
    rsrange.location = 0;//index是在头文件中申请好的全局变量.int型 初始值为0
    NSRange xrange = [strSplit rangeOfString:@"<"];
    if (xrange.length ==0)
    {
        return @"";
    }
    int x = xrange.location;
    
    NSRange yrange = [strSplit rangeOfString:@">"];
    
    int y = yrange.location;
    NSString *result = [strSplit substringFromIndex:x+1];
    result = [result substringToIndex:y-x-1];
    return result;
}

-(IBAction)dismissKeyBoard:(id)sender
{  
    [m_contentTView resignFirstResponder];  
} 
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
-(BOOL)textViewShouldReturn:(UITextView *)textView
{
    [textView resignFirstResponder];
    return YES;
}
- (void)viewDidUnload 
{
    [super viewDidUnload];
    self.m_navBar = nil;
}

- (void)dealloc 
{
	[m_toContainerView release];
	[m_contentTView release];
	[m_subjectTF release];
	[m_mainView release];
	[m_friC release];
    [m_mailCCfri release];
	[m_navBar release];
	[super dealloc];
}

#pragma mark -
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	switch (indexPath.row) 
	{
		case 0:
			return m_toContainerView.frame.size.height;
		case 1:
			return m_ccContainerView.frame.size.height;;
            
        case 2:
			return CONTROL_VIEW_HEIGH;
		case 3:
        {
            CGFloat height = m_contentTView.frame.size.height;
			return height;
        }
        //return 250.0;
	}
	return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return 4;
}


//******************************************************
// Method:     tableView
// Access:     public 
// Returns:    BOOL
// Parameter:  indexPath
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	static NSString *CellIdentifier = @"Cell";

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) 
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}
	
	if(indexPath.row == 0)
	{
		UIButton *accBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
		[accBtn addTarget:self action:@selector(callFriendList:) forControlEvents:UIControlEventTouchUpInside];
		cell.accessoryView = accBtn;
		[cell.contentView addSubview:m_toContainerView];
	}
    
    if(indexPath.row == 1)
	{
        UIButton *accBtn = [UIButton buttonWithType:UIButtonTypeContactAdd];
		[accBtn addTarget:self action:@selector(callCCFriendList:) forControlEvents:UIControlEventTouchUpInside];
		cell.accessoryView = accBtn;
		[cell.contentView addSubview:m_ccContainerView];
	}
	if(indexPath.row == 2)
	{
		[cell.contentView addSubview:m_subjectContainerView];
	}
	if(indexPath.row == 3)
	{
        m_mailCellView = cell;
        m_mailContenView = cell.contentView;
        cell.accessoryView = nil;
		[m_mailCellView addSubview:m_contentTView];
	}
	return cell;
}

#pragma mark -
#pragma textView

//******************************************************
// Method:     textViewTextDidChange
// Access:     public 
// Returns:    BOOL
// Parameter:  notif
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)textViewTextDidChange:(NSNotification*)notif
{
//	if([notif object] == contentTView)
//	{
//		NSString *text = contentTView.text;
//		if([text length] > 150)
//			[contentTView setText:[text substringToIndex:([text length]-1)]];
//	}
}

//******************************************************
// Method:     textViewShouldBeginEditing
// Access:     public 
// Returns:    BOOL
// Parameter:  textView
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
//	if(toContainerView.frame.size.height > 88)
//	{
//		[mainView setFrame:CGRectOffset(mainView.frame, 0.0, -120.0)];
//		offsetFlag = YES;
//	}
//    if(ccContainerView.frame.size.height > 88)
//	{
//		[mainView setFrame:CGRectOffset(mainView.frame, 0.0, -120.0)];
//		offsetFlag = YES;
//	}
	return YES;
}

//******************************************************
// Method:     textViewDidBeginEditing
// Access:     public 
// Returns:    BOOL
// Parameter:  textField
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (IBAction)textViewDidBeginEditing:(UITextView *)textView
{
    
	[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
	[UIView setAnimationDuration:0.30f];  
	
	m_mainView.frame = CGRectMake(0.0, 44.0, 320.0, 200);
	[UIView commitAnimations];
}

//******************************************************
// Method:     textViewDidEndEditing
// Access:     public 
// Returns:    BOOL
// Parameter:  textField
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (IBAction)textViewDidEndEditing:(UITextView *)textView
{
	[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
	[UIView setAnimationDuration:0.30f];  
	
	m_mainView.frame = m_rect;
	[UIView commitAnimations];
}
#pragma mark --
#pragma textField

//******************************************************
// Method:     textFieldDidBeginEditing
// Access:     public 
// Returns:    BOOL
// Parameter:  textField
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
	[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
	[UIView setAnimationDuration:0.30f];  
	
	m_mainView.frame = CGRectMake(0.0, 44.0, 320.0, 200);
	[UIView commitAnimations];
}

- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
	[UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
	[UIView setAnimationDuration:0.30f];  
	m_mainView.frame = m_rect;
	[UIView commitAnimations];
}

//******************************************************
// Method:     textFieldTextDidChange
// Access:     public 
// Returns:    BOOL
// Parameter:  notif
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)textFieldTextDidChange:(NSNotification*)notif
{
    if([notif object] == m_toSendTF)
	{
		NSString *text = m_toSendTF.text;
        NSLog(@"%@", text);

//		if([text length] > 21)
//			[m_toSendTF setText:[text substringToIndex:([text length]-1)]];
	}
    
	if([notif object] == m_ccSendTF)
	{
        

	}
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == m_toSendTF)
    {
 
        NSLog(@"%@", string);
        
        if ([string isEqualToString:@" "]) 
        {
            NSString *text = [m_toSendTF.text substringToIndex:range.location];
            NSString* strContent  = [NSString stringWithFormat:@"%@%@",text,@";"];
            m_toSendTF.text = strContent;
            [m_toSendTF setTextColor:[UIColor blueColor]];
        }
    
    }
    return YES;
}

//******************************************************
// Method:     textFieldShouldBeginEditing
// Access:     public 
// Returns:    BOOL
// Parameter:  textField
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
//	if(offsetFlag)
//	{
//		[mainView setFrame:CGRectOffset(mainView.frame, 0.0, 120.0)];
//	}
//	offsetFlag = NO;
	return YES;
}
#pragma mark -

//******************************************************
// Method:     addContact
// Access:     public 
// Returns:    BOOL
// Parameter:  sender
// Note:	   增加发送邮件列表
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)addMailContact:(id)obj
{	
	if ([self addReceiver:obj] == FALSE) {
        return;
    }
	[self refreshReceiverView:MSGV_ADD_CONTACT];
	
	[self dismissModalViewControllerAnimated:YES];
}

//******************************************************
// Method:     receiveViewClicked
// Access:     public 
// Returns:    BOOL
// Parameter:  sender
// Note:	   增加抄送邮件列表
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)addCCMailContact:(id)obj
{	
    if ([self addCCReceiver:obj] == FALSE) {
        return;
    }
	[self refreshCCReceiverView:MSGV_ADD_CONTACT];
	
	[self dismissModalViewControllerAnimated:YES];
}

//******************************************************
// Method:     receiveViewClicked
// Access:     public 
// Returns:    BOOL
// Parameter:  sender
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)receiveViewClicked:(id)sender
{
	MailCCMsgReceiverView *msgRV = (MailCCMsgReceiverView*)sender;
	int index = -1;
    int sendIndex = -1;
	for(NSString *idd in m_totalAddrArray)
	{
		if(idd == msgRV.recid)
		{
			index = [m_totalAddrArray indexOfObject:idd];
            sendIndex = [m_sendAddrArray indexOfObject:idd];
			break;
		}
	}
	if(index != -1)
	{
		[m_totalAddrArray removeObjectAtIndex:index];
        [m_sendAddrArray removeObjectAtIndex:sendIndex];
	}
	
	if([msgRV superview] != nil)
	{
		[msgRV removeFromSuperview];
		[self refreshReceiverView:MSGV_DEL_CONTACT];
	}
}
//******************************************************
// Method:     receiveCCViewClicked
// Access:     public 
// Returns:    BOOL
// Parameter:  sender
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)receiveCCViewClicked:(id)sender
{
	MailCCMsgReceiverView *msgRV = (MailCCMsgReceiverView*)sender;
	int index   = -1;
    int ccIndex = -1;
	for(NSString *idd in m_totalAddrArray)
	{
		if(idd == msgRV.recid)
		{
			index   = [m_totalAddrArray indexOfObject:idd];
            ccIndex = [m_ccAddrArray indexOfObject:idd];
			break;
		}
	}
	if(index != -1)
	{
		[m_totalAddrArray removeObjectAtIndex:index];
        [m_ccAddrArray removeObjectAtIndex:ccIndex];
	}
	
	if([msgRV superview] != nil)
	{
		[msgRV removeFromSuperview];
		[self refreshCCReceiverView:MSGV_DEL_CONTACT];
	}
}
#pragma mark -
//******************************************************
// Method:     addReceiver
// Access:     public 
// Returns:    BOOL
// Parameter:  recObj
// Note:	   增加抄送
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(BOOL)addReceiver:(id)recObj
{
	//--- 条件核对 ---
	if(recObj == nil)
		return FALSE;
	NSDictionary *dict = (NSDictionary*)recObj;
	NSString *user_id = [dict objectForKey:@"t_1_mail"];
	NSLog(@"contact name:%@",user_id);
	
	for(NSString *idd in m_totalAddrArray)
	{
		if([idd isEqualToString:user_id])
		{
			[self dismissModalViewControllerAnimated:YES];
			return FALSE; 
		}
	}
//	if([toArray count] == 5)
//	{
//		[self dismissModalViewControllerAnimated:YES];
//		tipAlert = [[UIAlertView alloc] initWithTitle:@"\n" message:@"最多5个好友" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
//		[tipAlert show];
//		tipTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(dismissTipAlert:) userInfo:nil repeats:NO];
//		return;
//	}
	//--------
	
	//-----计算接受者大小尺寸
	MailMsgReceiverView *msgReV = [[MailMsgReceiverView alloc] initWithObject:dict];
	msgReV.delegate = self;
	
	int count   = [[m_toContainerView subviews] count];
	int length  = count - m_indexOfFirstNewLine;
	
	NSArray *lineCheckArray = [[m_toContainerView subviews] objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(m_indexOfFirstNewLine, length)]];
	
	int totalWidth = 0;
	int oldWidth   = 0;
	for(MailMsgReceiverView *mv in lineCheckArray)
	{
        if ([mv isKindOfClass:[UITextField class]] == YES)
        {
            continue;
        }
        if ([mv isKindOfClass:[UILabel class]] == YES)
        {
            continue;
        }
		totalWidth += mv.frame.size.width;
		oldWidth   += mv.frame.size.width;    //从第一个到最后一个宽度
	}
	totalWidth += msgReV.frame.size.width; //查看增加后，当前宽度是否大于最大宽度
	
	if(totalWidth < 250)
	{
		msgReV.center = CGPointMake(oldWidth + msgReV.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER+m_receiverRowIndex*ADD_CONTACT_HEIGH);
	}
	else 
	{
		m_indexOfFirstNewLine = [[m_toContainerView subviews] count];  //-1 then +1
		++m_receiverRowIndex;
		
		msgReV.center = CGPointMake(msgReV.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER+m_receiverRowIndex*ADD_CONTACT_HEIGH);
	}
	[m_toContainerView addSubview:msgReV];
	[m_totalAddrArray addObject:user_id];
    [m_sendAddrArray addObject:user_id];
	[msgReV release];
	//----------
    return TRUE;
}

//******************************************************
// Method:     addCCReceiver
// Access:     public 
// Returns:    BOOL
// Parameter:  recObj
// Note:	   增加抄送
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(BOOL)addCCReceiver:(id)recObj
{
    //--- 条件核对 ---
	if(recObj == nil)
		return FALSE;
	NSDictionary *dict = (NSDictionary*)recObj;
	NSString *user_id = [dict objectForKey:@"t_1_mail"];
	NSLog(@"contact name:%@",user_id);
	
	for(NSString *idd in m_totalAddrArray)
	{
		if([idd isEqualToString:user_id])
		{
			[self dismissModalViewControllerAnimated:YES];
			return FALSE;
		}
	}
    //	if([toArray count] == 5)
    //	{
    //		[self dismissModalViewControllerAnimated:YES];
    //		tipAlert = [[UIAlertView alloc] initWithTitle:@"\n" message:@"最多5个好友" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    //		[tipAlert show];
    //		tipTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(dismissTipAlert:) userInfo:nil repeats:NO];
    //		return;
    //	}
	//--------
	
	//-----计算接受者大小尺寸
	MailCCMsgReceiverView *msgReV = [[MailCCMsgReceiverView alloc] initWithObject:dict];
	msgReV.delegate = self;
	
	int count   = [[m_ccContainerView subviews] count];
	int length = count - m_ccIndexOfFirstNewLine;
	
	NSArray *lineCheckArray = [[m_ccContainerView subviews] objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(m_ccIndexOfFirstNewLine, length)]];
	
	int totalWidth = 0;
	int oldWidth = 0;
	for(MailCCMsgReceiverView *mv in lineCheckArray)
	{
        if ([mv isKindOfClass:[UITextField class]] == YES)
        {
            continue;
        }
        if ([mv isKindOfClass:[UILabel class]] == YES)
        {
            continue;
        }
		totalWidth += mv.frame.size.width;
		oldWidth += mv.frame.size.width;    //从第一个到最后一个宽度
	}
	totalWidth += msgReV.frame.size.width; //查看增加后，当前宽度是否大于最大宽度
	
	if(totalWidth < 250)
	{
		msgReV.center = CGPointMake(oldWidth + msgReV.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER + m_ccReceiverRowIndex * ADD_CONTACT_HEIGH);
	}
	else 
	{
		m_ccIndexOfFirstNewLine = [[m_ccContainerView subviews] count];  //-1 then +1
		++m_ccReceiverRowIndex;
		
		msgReV.center = CGPointMake(msgReV.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER +m_ccReceiverRowIndex * ADD_CONTACT_HEIGH);
	}
	[m_ccContainerView addSubview:msgReV];
	[m_totalAddrArray addObject:user_id];
    [m_ccAddrArray addObject:user_id];
	[msgReV release];
	//----------}
    return  TRUE;
}

//******************************************************
// Method:     callCCFriendList
// Access:     public 
// Returns:    void
// Parameter:  sender
// Note:	   增加抄送邮件列表
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)callCCFriendList:(id)sender
{

    m_mailCCfri = [[MailCCFriendList alloc] initWithNibName:@"MailCCFriendList" bundle:nil];
    m_mailCCfri.m_mailCCFriendListDelegate = self;

	[self presentModalViewController:m_mailCCfri animated:YES];
}

-(void)callFriendList:(id)sender
{

    m_friC = [[MailFriendList alloc] initWithNibName:@"MailFriendList" bundle:nil];
    m_friC.m_mailFriendListDelegate = self;
	[self presentModalViewController:m_friC animated:YES];
}
#pragma  mark --send
-(void)onNavigation
{
    self.m_navBar.hidden = YES;
    //[self.navigationController setNavigationBarHidden:YES];
    [self.navigationController popViewControllerAnimated :YES];
}
-(IBAction)onSend:(id)sender
{
    //取得收件人地址
    NSString * strToSend = m_toSendTF.text;
    NSArray * arrayToSend =   [strToSend componentsSeparatedByString:@";"];
    NSLog(@"%@", arrayToSend);
    
    //取得抄送人地址
    NSString * strCCSend = m_ccSendTF.text;
    NSArray * arrayCCSend =   [strCCSend componentsSeparatedByString:@";"];
    NSLog(@"%@", arrayCCSend);
    
	NSString *subj      = m_subjectTF .text;
	NSString *content   = m_contentTView.text;
    
    if([m_sendAddrArray count] == 0 && [arrayToSend count] == 0)
	{
		m_tipAlert = [[UIAlertView alloc] initWithTitle:@"\n" message:@"请选收件人" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
		[m_tipAlert show];
		m_tipTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(dismissTipAlert:) userInfo:nil repeats:NO];
		return;
	}
    
	if([subj isEqualToString:@""] || [content isEqualToString:@""])
	{
		m_tipAlert = [[UIAlertView alloc] initWithTitle:@"\n" message:@"请完成标题和内容" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
		[m_tipAlert show];
		m_tipTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(dismissTipAlert:) userInfo:nil repeats:NO];
        [m_subjectTF resignFirstResponder];
		return;
	}
    
    //替换< &lt;    >   &gt;
    NSLog(@"1-----%@\n---------",content);
    content=[content stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
    NSLog(@"2-----%@\n---------",content);
    content=[content stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    NSLog(@"3-----%@\n---------",content);

    

    
    /*发送到服务器*/
    XmlRpc *xml = [[[XmlRpc alloc] init] autorelease];   
    
    //得到发件人的名字
//    NSString* strMemberNickName = [[Session share] getMemberNickName];
    
    //取得接收人地址
    NSString* sendAddrArray = [m_sendAddrArray  componentsJoinedByString:@";"];
    NSString* SendTV        = [arrayToSend componentsJoinedByString:@";"];
    sendAddrArray = [NSString stringWithFormat:@"%@;%@",sendAddrArray,SendTV];
    
    //取得抄送人地址
    NSString* ccSendAddrArray = [m_ccAddrArray  componentsJoinedByString:@";"];
    NSString* ccSendTV        = [arrayCCSend componentsJoinedByString:@";"];
    ccSendAddrArray = [NSString stringWithFormat:@"%@;%@",ccSendAddrArray,ccSendTV];
    
    //得到当前时间
//    NSString* strCurrentTime = [self getCurrentTime];
    NSLog(@"send to Server:%@",m_sendAddrArray);
    
 /*************************************************************** 
    设置发送的数据
 ***************************************************************/ 

    NSString* id             =   [GUID getGUIDString];
    NSString* mailNewShareId =   [GUID getGUIDString];
    NSString* employee_id    =   [[Session share] getMemberID];
    NSString* origin_id      =   @"";
    NSString* origin_type    =   @"";
    
    //取得发送人地址
    NSString* mail_send_address = [Session share].MailAddress;
    NSString* mailShareParentId = @"";
    
    switch (m_mailComType) 
    {
        case NEW_COMPOSER:
        {
            origin_id           = @"";
            origin_type         = @"";
            mailShareParentId   = mailNewShareId;
            break;
        }
            
        case REVERSE_COMPOSER:
        {
            origin_type        = @"01";
            NSString* id1;
            NSString* parentid;
            id1          = [m_mailDetailMessage.m_mailListInfo objectForKey:@"id"];
            parentid      = [m_mailDetailMessage.m_mailListInfo objectForKey:@"parentid"];
            NSLog(@"id1=%@,parentid=%@",id1,parentid);
            
            origin_id          = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailShareId"];
            mailShareParentId  = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailParentId"];
            NSLog(@"id1=%@,parentid=%@",origin_id,mailShareParentId);
            break;
        }
        case TRANSMIT_COMPOSER:
        {
            origin_type        = @"03";
            origin_id          = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailShareId"];
            mailShareParentId  = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailParentId"];
            break;
        }
        default:
            break;
    }

    
    NSMutableDictionary * sendNewMailParm = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                             id,                    @"id",
                                             m_subjectTF .text,     @"subject",
                                             content,               @"content_txt",
                                             @"",                   @"auditing_state",
                                             origin_id,             @"origin_id",
                                             origin_type,           @"origin_type",
                                             mailNewShareId,        @"mailShareId", 
                                             mailShareParentId,     @"mailShareParentId",
                                             employee_id,           @"employee_id",   
                                             @"02",                 @"box", 
                                             mail_send_address,     @"sendaddress",
                                             sendAddrArray,         @"receiveaddress",
                                             ccSendAddrArray,       @"ccaddress", 
                                             @"",                   @"baddress",
                                             @"0",                  @"many_send_flag", 
                                             nil];
    
    [xml sendNewMail:sendNewMailParm];
    
	m_tipAlert = [[UIAlertView alloc] initWithTitle:@"－－－－邮件已发送－－－－" message:m_contentTView.text delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
	[m_tipAlert show];
	m_tipTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(dismissTipAlert:) userInfo:nil repeats:NO];
    
    //返回到前一个页面
    [self onNavigation];
}

//******************************************************
// Method:     getMailShareParentId
// Access:     public 
// Returns:    void
// Parameter:  
// Note:	   getMailShareParentId
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(NSString*)getMailShareParentId
{
    //    String id = (String)mailShare.get("id");
    //    String shareParentId = (String)mailShare.get("parent_employee_share_id");
    //    
    //    if(null != id)
    //    {
    //        if(id.equals(shareParentId))
    //        {
    //            mailEditBean.setMailShareParentId((String)mailShare.get("id"));
    //        }
    //        else
    //        {
    //            mailEditBean.setMailShareParentId(shareParentId);
    //        }
    //    }
    //    else
    //    {
    //        mailEditBean.setMailShareParentId(mailEditBean.getMailShareId());
    //    }
//    NSString* mailShareParentId = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"parentid"];
//    NSString* originID = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"id"];
    return @"";
}
//******************************************************
// Method:     getCurrentTime
// Access:     public 
// Returns:    void
// Parameter:  
// Note:	   得到当前时间
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (NSString *)getCurrentTime
{
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps;
    comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
    return [NSString stringWithFormat:@"%.4d-%.2d-%.2d %.2d:%.2d:%.2d",[comps year],[comps month],[comps day],[comps hour],[comps minute],[comps second]];
}
-(IBAction)onSave:(id)sender
{
    //取得收件人地址
    NSString * strToSend = m_toSendTF.text;
    NSArray * arrayToSend =   [strToSend componentsSeparatedByString:@";"];
    NSLog(@"%@", arrayToSend);
    
    //取得抄送人地址
    NSString * strCCSend = m_ccSendTF.text;
    NSArray * arrayCCSend =   [strCCSend componentsSeparatedByString:@";"];
    NSLog(@"%@", arrayCCSend);
    
//	NSString *subj      = m_subjectTF .text;
	NSString *content   = m_contentTView.text;
    /*发送到服务器*/
    XmlRpc *xml = [[[XmlRpc alloc] init] autorelease];   
    
    //得到发件人的名字
//    NSString* strMemberNickName = [[Session share] getMemberNickName];
    
    //取得接收人地址
    NSString* sendAddrArray = [m_sendAddrArray  componentsJoinedByString:@";"];
    NSString* SendTV        = [arrayToSend componentsJoinedByString:@";"];
    sendAddrArray = [NSString stringWithFormat:@"%@;%@",sendAddrArray,SendTV];
    
    //取得抄送人地址
    NSString* ccSendAddrArray = [m_ccAddrArray  componentsJoinedByString:@";"];
    NSString* ccSendTV        = [arrayCCSend componentsJoinedByString:@";"];
    ccSendAddrArray = [NSString stringWithFormat:@"%@;%@",ccSendAddrArray,ccSendTV];
    
    
    //替换< &lt;    >   &gt;
    NSLog(@"1-----%@\n---------",content);
    content=[content stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
    NSLog(@"2-----%@\n---------",content);
    content=[content stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    NSLog(@"3-----%@\n---------",content);
    
    //得到当前时间
//    NSString* strCurrentTime = [self getCurrentTime];
    NSLog(@"send to Server:%@",m_sendAddrArray);
    /*************************************************************** 
     设置发送的数据
     ***************************************************************/ 
    
    NSString* guid             =   [GUID getGUIDString];
    NSString* mailNewShareId =   [GUID getGUIDString];
    NSString* employee_id    =   [[Session share] getMemberID];
    NSString* origin_id      =   @"";
    NSString* origin_type    =   @"";
    
    //取得发送人地址
    NSString* mail_send_address = [Session share].MailAddress;
    NSString* mailShareParentId = @"";
    
    switch (m_mailComType) 
    {
        case NEW_COMPOSER:
        {
            origin_id           = @"";
            origin_type         = @"";
            mailShareParentId   = mailNewShareId;
            break;
        }
            
        case REVERSE_COMPOSER:
        {
            
            
            origin_type        = @"01";
            NSString* id1;
            NSString* parentid;
            id1          = [m_mailDetailMessage.m_mailListInfo objectForKey:@"id"];
            parentid      = [m_mailDetailMessage.m_mailListInfo objectForKey:@"parentid"];
            NSLog(@"id1=%@,parentid=%@",id1,parentid);
            
            origin_id          = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailShareId"];
            mailShareParentId  = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailParentId"];
            NSLog(@"id1=%@,parentid=%@",origin_id,mailShareParentId);
            
            
            origin_type        = @"01";
            origin_id          = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailShareId"];
            mailShareParentId  = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailParentId"];
            break;
        }
        case TRANSMIT_COMPOSER:
        {
            origin_type        = @"03";
            origin_id          = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailShareId"];
            mailShareParentId  = [m_mailDetailMessage.m_mailDetailInfo objectForKey:@"mailParentId"];
            break;
        }
        default:
            break;
    }
    
    
    NSMutableDictionary * saveNewMailParm = [[NSMutableDictionary alloc] 
                                             initWithObjectsAndKeys:
                                             guid,                  @"id",
                                             m_subjectTF.text,      @"subject",
                                             content,               @"content_txt",
                                             @"",                   @"auditing_state",
                                             origin_id,             @"origin_id",
                                             origin_type,           @"origin_type",
                                             mailNewShareId,        @"mailShareId", 
                                             mailShareParentId,     @"mailShareParentId",
                                             employee_id,           @"employee_id",   
                                             @"04",                 @"box", 
                                             mail_send_address,     @"sendaddress",
                                             sendAddrArray,         @"receiveaddress",
                                             ccSendAddrArray,       @"ccaddress", 
                                             @"",                   @"baddress",
                                             @"0",                  @"many_send_flag", 
                                             nil];
    
    [xml saveNewMail:saveNewMailParm];
   //[xml release];
   // [saveNewMailParm release];

    
	NSLog(@"save to Server:%@",m_totalAddrArray);
	m_tipAlert = [[UIAlertView alloc] initWithTitle:@"－－－－邮件已保存－－－－" message:m_contentTView.text delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
	[m_tipAlert show];
	m_tipTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(dismissTipAlert:) userInfo:nil repeats:NO];
}
-(IBAction)onCancel:(id)sender
{
	 //[toArray removeAllObjects];
//	 for(UIView *subV in [toContainerView subviews])
//	 {
//		 [subV removeFromSuperview];
//	 }
//	[mainView reloadData];
//	
//	 [subjectTF setText:@""];
//	 [contentTView setText:@""];
	
	//[self dismissModalViewControllerAnimated:YES];
}
-(void)refreshReceiverView:(int)flag
{	
	if(flag == MSGV_DEL_CONTACT)
	{
		NSMutableArray *temA = [[NSMutableArray alloc] init]; 
		for(MailMsgReceiverView *msgV in [m_toContainerView subviews])
		{
            if ([msgV isKindOfClass:[UITextField class]] == YES)
            {
                continue;
            }
            if ([msgV isKindOfClass:[UILabel class]] == YES)
            {
                continue;
            }
			[temA addObject:msgV];
			[msgV removeFromSuperview];
		}
		if ([temA count] ==0)
        {
            //删除添加联系人的行数，变为第一行
            m_receiverRowIndex = 0;
        }else
        {
            m_receiverRowIndex = 1;
        }
		
		m_indexOfFirstNewLine = 2;
		//toContainerView.frame = CGRectMake(0.0, 0.0, 320, 44.0+receiverRowIndex*44.0);
		[m_mainView reloadData];
		
		for(MailMsgReceiverView *msgV1 in temA)
		{

			int count = [[m_toContainerView subviews] count];
			int length = count - m_indexOfFirstNewLine;
			
			NSArray *lineCheckArray = [[m_toContainerView subviews] objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(m_indexOfFirstNewLine, length)]];
			
			int totalWidth = 0;
			int oldWidth = 0;
			for(MailMsgReceiverView *mv in lineCheckArray)
			{
				totalWidth += mv.frame.size.width;
				oldWidth += mv.frame.size.width;  //从第一个到最后一个宽度
			}
			totalWidth += msgV1.frame.size.width; ////查看增加后，当前宽度是否大于最大宽度
            
			if(totalWidth < 250)
			{
				msgV1.center = CGPointMake(oldWidth + msgV1.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER+m_receiverRowIndex*ADD_CONTACT_HEIGH);
			}
			else 
			{
				m_indexOfFirstNewLine = [[m_toContainerView subviews] count];  //-1 then +1
				++m_receiverRowIndex;
				
				msgV1.center = CGPointMake(msgV1.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER+m_receiverRowIndex*ADD_CONTACT_HEIGH);
			}
			[m_toContainerView addSubview:msgV1];
		}
		[temA release];
		m_toContainerView.frame = CGRectMake(0.0, 0.0, 320, ADD_CONTACT_HEIGH+m_receiverRowIndex*ADD_CONTACT_HEIGH);
        //删除后，恢复下一次，为第二行
        m_receiverRowIndex = 1;
	}
	if(flag == MSGV_ADD_CONTACT)
	{
		m_toContainerView.frame = CGRectMake(0.0, 0.0, 320, ADD_CONTACT_HEIGH+m_receiverRowIndex*ADD_CONTACT_HEIGH);
	}
	[m_mainView reloadData];
}
/*
 抄送邮件列表
 */
-(void)refreshCCReceiverView:(int)flag
{	
	if(flag == MSGV_DEL_CONTACT)
	{
		NSMutableArray *temA = [[NSMutableArray alloc] init]; 
		for(MailCCMsgReceiverView *msgV in [m_ccContainerView subviews])
		{
            if ([msgV isKindOfClass:[UITextField class]] == YES)
            {
                continue;
            }
            if ([msgV isKindOfClass:[UILabel class]] == YES)
            {
                continue;
            }
			[temA addObject:msgV];
			[msgV removeFromSuperview];
		}
		if ([temA count] ==0)
        {
            //删除添加联系人的行数，变为第一行
            m_ccReceiverRowIndex = 0;
        }else
        {
            m_ccReceiverRowIndex = 1;
        }
		
		m_ccIndexOfFirstNewLine = 2;
		//toContainerView.frame = CGRectMake(0.0, 0.0, 320, 44.0+receiverRowIndex*44.0);
		[m_mainView reloadData];
		
		for(MailCCMsgReceiverView *msgV1 in temA)
		{
			int count  = [[m_ccContainerView subviews] count];
			int length = count - m_ccIndexOfFirstNewLine;
			
			NSArray *lineCheckArray = [[m_ccContainerView subviews] objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(m_ccIndexOfFirstNewLine, length)]];
			
			int totalWidth = 0;
			int oldWidth   = 0;
			for(MailCCMsgReceiverView *mv in lineCheckArray)
			{
				totalWidth += mv.frame.size.width;
				oldWidth   += mv.frame.size.width;  //从第一个到最后一个宽度
			}
			totalWidth += msgV1.frame.size.width; ////查看增加后，当前宽度是否大于最大宽度
            
			if(totalWidth < 250)
			{
				msgV1.center = CGPointMake(oldWidth + msgV1.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER+m_ccReceiverRowIndex*ADD_CONTACT_HEIGH);
			}
			else 
			{
				m_ccIndexOfFirstNewLine = [[m_ccContainerView subviews] count];  //-1 then +1
				++m_ccReceiverRowIndex;
				
				msgV1.center = CGPointMake(msgV1.frame.size.width/2 + 5.0, ADD_CONTACT_CENTER+m_ccReceiverRowIndex*ADD_CONTACT_HEIGH);
			}
			[m_ccContainerView addSubview:msgV1];
		}
		[temA release];
		m_ccContainerView.frame = CGRectMake(0.0, 0.0, 320, ADD_CONTACT_HEIGH+m_ccReceiverRowIndex*ADD_CONTACT_HEIGH);
        //删除后，恢复下一次，为第二行
        m_ccReceiverRowIndex = 1;
	}
	if(flag == MSGV_ADD_CONTACT)
	{
		m_ccContainerView.frame = CGRectMake(0.0, 0.0, 320, ADD_CONTACT_HEIGH+m_ccReceiverRowIndex*ADD_CONTACT_HEIGH);
	}
	[m_mainView reloadData];
}
//******************************************************
// Method:     dismissTipAlert
// Access:     public 
// Returns:    void
// Parameter:  void
// Note:	   弹出popup消失
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)dismissTipAlert:(NSTimer*)ti
{
	[m_tipTimer invalidate];
	[m_tipAlert dismissWithClickedButtonIndex:0 animated:YES];
	[m_tipAlert release];
}

//******************************************************
// Method:     setMailDetailObj
// Access:     public 
// Returns:    void
// Parameter:  mailComposer
// Note:	   保存mail详细页面的指针
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)setMailDetailObj:(MailDetailMessage*)mailComposer
{
    m_mailDetailMessage = mailComposer;
}
#pragma mark －－
#pragma mark －－－－－－－－UITextView 事件－－－－－－－－－－－－
#pragma mark －－
//******************************************************
// Method:     shouldChangeTextInRange
// Access:     public 
// Returns:    void
// Parameter:  range
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (BOOL)textView: (UITextView *)textview shouldChangeTextInRange: (NSRange)range replacementText: (NSString *)text 
{
    
    //////////////////////////////////////////////////////////////////

//        if ([text isEqualToString:@"\n"])
//        {
//            CGRect contenViewFrame = mailContenView.frame;
//            CGRect CellViewFrame = mailCellView.frame;
//            contenViewFrame.size.height +=25;
//            CellViewFrame.size.height +=25;
//            mailContenView.frame   = contenViewFrame;
//            mailCellView.frame   =CellViewFrame;
//            contentTView.frame   = CGRectMake(10.0, 0.0, 310.0, size.height+25);
//            //mainView.frame = CGRectMake(0.0, 44.0, 320.0, 200);
////            mailContenCell.frame = mailContentRect;
//            
//            rect = mainView.tableFooterView.frame;
//            rect.origin.y += 25;
//            mainView.tableFooterView.frame = rect;
//            
//            
//            
//            rect = self.view.frame;
//            rect = mainView.frame;
//            [contentTView sizeToFit];
//            [mailContenCell sizeToFit];
            //[mainView sizeToFit];
           
//            NSRange cursorPosition = range;
//            NSInteger index = cursorPosition.location;
//            NSMutableString *content = [[NSMutableString alloc] initWithString:textview.text];  
//            [content insertString:text atIndex:index];
//            textview.text = content;
//            [mainView reloadData];
//        }
//    
//	if (cell == nil) 
//	{
//		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//	}
//    for (UIView* cellView in cell.contentView.subviews)
//    {
//        if ([cellView isKindOfClass:[UITextView class]]) 
//        {
//            NSLog(@"success");
//        } 
//    }
    
    //        UITableViewCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
    //        //定位光标
    //        
    //        NSRange range = [opinion selectedRange];
    //        NSMutableString *top = [[NSMutableString alloc] initWithString:[opinion text]];
    //        NSString *addName = [NSString stringWithFormat:@"%@、",cell.textLabel.text];
    //        [top insertString:addName atIndex:range.location];
    //        opinion.text = top;
    //        [top release];
    
    
    //        NSRange cursorPosition = [textview selectedRange];
    //        NSInteger index = cursorPosition.location;
    //        NSMutableString *content = [[NSMutableString alloc] initWithString:textview.text];  
    //        [content insertString:@"XXXXX" atIndex:index];
    //        textview.text = content;
    //        [content release]; 
            NSRange cursorPosition = range;
            NSInteger index = cursorPosition.location;
            NSMutableString *content = [[NSMutableString alloc] initWithString:textview.text];  
            [content insertString:text atIndex:index];
            //textview.text = content;
            [content release]; 

//    if ([text isEqualToString:@"\n"])
//    {
//        int a = 0;
//        a= 9;
//    }
    
    return YES;
} 
- (void)textViewDidChange:(UITextView *)textView
{
    //NSRange cursorPosition  = [textView selectedRange];
    //NSInteger index         = cursorPosition.location;
    m_mailContent             = [[NSMutableString alloc]initWithString:textView.text];  
    //[content insertString:text atIndex:index];
    //textview.text = content;
    //[content release]; 
    //[mainView reloadData];
}
@end
